package org.jerry.virtualoperator.controller;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import lombok.extern.slf4j.Slf4j;
import org.jerry.virtualoperator.form.VsmsTemplateCreateForm;
import org.jerry.virtualoperator.vo.Click;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Slf4j
@RestController
@RequestMapping("api/vsms/template")
public class VsmsTemplateController {

    @Autowired
    Cache<Long, String> templateBackCache;

    static ObjectMapper mapper = new ObjectMapper();

    @PostMapping
    public Click<Long> create(@RequestBody @Validated VsmsTemplateCreateForm form) {
        log.info("create template form : {}", form);
        long templateId = System.currentTimeMillis();
        templateBackCache.put(templateId, form.getCallbackUrl());
        return Click.succ(templateId);
    }

    @GetMapping("/{id}")
    public Click<?> get(@PathVariable("id") long id) {
        Map<String, Object> template = new HashMap<>(2);
        template.put("id", id);
        template.put("status", "PASSED");
        return Click.succ(template);
    }

    @PostMapping("/reportion")
    public String report(HttpServletRequest request) throws IOException {
        ObjectReader reader = mapper.readerFor(List.class);
        List report = reader.readValue(request.getInputStream());
        log.info("receive template report: {}", report);

        return "SUCCESS";
    }
}
